package com.ddd.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by zhouxj6112 on 2019/12/15.
 */
public class AESUtil {

    private static final String KEY_ALGORITHM = "AES";
    private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/NoPadding";

    /**
     * 加密
     *
     * @param content  需要加密的内容
     * @param password 加密密码,长度必须16位
     * @return
     */
    public static String encrypt(String content, String password)
    {
        try
        {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = content.getBytes("UTF-8");
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(password.getBytes(), KEY_ALGORITHM);
            IvParameterSpec ivspec = new IvParameterSpec(password.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            byte[] msgBytes = Base64.encodeBase64(encrypted);
            return new String(msgBytes);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }

    }

    /**
     * 解密
     *
     * @param content  待解密内容
     * @param password 解密密钥,长度必须16位
     * @return
     */
    public static String decrpyt(String content, String password)
    {
        try
        {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = Base64.decodeBase64(content);
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(password.getBytes(), KEY_ALGORITHM);
            IvParameterSpec ivspec = new IvParameterSpec(password.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new String(encrypted, "UTF-8");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

}
